<template>
  <div>
    <div class="div-inquire">
      <div class="div-inquire-left">
        <el-form v-model="params" ref="paramsRefs" inline>
          <el-form-item label="操作人" label-width="70px" prop="name">
            <el-input v-model="params.name" placeholder="请输入操作人" @clear="clearName" clearable></el-input>
          </el-form-item>
        </el-form>
        <el-button  @click="clickReset" plain>重置</el-button>
        <el-button @click="clickSearch" type="primary">搜索</el-button>
      </div>
      <div class="div-inquire-right">
        <batch-import :type="2" :customerType="1" :customerId="id"></batch-import>
        <el-button icon="el-icon-download" type="primary" @click="clickExport" >数据导出</el-button>
        <el-button icon="el-icon-plus" type="primary" @click="addData">新增</el-button>
      </div>

    </div>
    <div class="div-table">
      <el-table
        ref="cooperationTableRefs"
        :data="tableData"
        :header-cell-style="{background:'#F5F7FA'}"
        style="width: 100%"
        v-loading="dataListLoading">
        <el-table-column label="进款金额（元）" prop="income" align="center">
          <template slot-scope="scope" >
            <el-input v-if="scope.row.edit" v-model.number="scope.row.income" placeholder="请输入进款金额" type='number' maxLength='9' @change="(val)=>{changeIncome(val,scope.row)}"  clearable></el-input>
            <span :class="[scope.row.typeId === 1 ? '' : scope.row.typeId === 2 ? 'error-color' : 'warning-color']" v-else>{{scope.row.income }}</span>
          </template>
        </el-table-column>
        <el-table-column label="进款明细"  prop="detail" align="center" show-overflow-tooltip>
          <template slot-scope="scope" >
            <el-input v-if="scope.row.edit" v-model.number="scope.row.detail"  placeholder="请填写进款明细" @focus="showIncomeDetail(scope)" @change="checkIncome"   readonly></el-input>
            <span v-else>{{scope.row.detail}}</span>
          </template>
        </el-table-column>
        <el-table-column label="业绩金额（元）" prop="perfor" align="center">
          <template slot-scope="scope" >
            <el-input v-if="scope.row.edit" v-model.number="scope.row.perfor" placeholder="请输入业绩金额" type='number' maxLength='9' clearable></el-input>
            <span v-else>{{scope.row.perfor}}</span>
          </template>
        </el-table-column>
        <el-table-column label="进款账号" prop="incomeAccountId" align="center">
          <template slot-scope="scope" >
            <el-select v-if="scope.row.edit" v-model="scope.row.incomeAccountId" placeholder="请选择进款账号" @focus="getDictListOptions" @change="changeIncomeAccount"  clearable>
              <el-option
                v-for="item in dictListOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"></el-option>
            </el-select>
            <span v-else>{{scope.row.incomeAccount}}</span>
          </template>
        </el-table-column>
        <el-table-column label="进款时间" prop="incomeDate" align="center">
          <template slot-scope="scope" >
            <el-date-picker
              v-if="scope.row.edit"
              v-model="scope.row.incomeDate"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="请输入进款时间"
              clearable
              style="width: 146px">
            </el-date-picker>
            <span v-else>{{scope.row.incomeDate}}</span>
          </template>
        </el-table-column>
<!--        <el-table-column prop="description" label="合同简述" align="center" show-overflow-tooltip>
          <template slot-scope="scope" >
            <el-input v-if="scope.row.edit" v-model="scope.row.description" placeholder="请输入合同简述"  clearable></el-input>
            <span v-else>{{scope.row.description}}</span>
          </template>
        </el-table-column>
        <el-table-column label="类型" prop="income" align="center">
          <template slot-scope="scope" >
            <el-select v-if="scope.row.edit" v-model="scope.row.typeId" placeholder="请选择类型" @focus="getTypeOption"  clearable>
              <el-option
                v-for="item in typeOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"></el-option>
            </el-select>
            <span v-else>{{scope.row.typeId === 1 ? '进款' : scope.row.typeId === 2 ? '退款' : '挂靠'}}</span>
          </template>

        </el-table-column>
        <el-table-column label="明细" prop="detail" align="center" show-overflow-tooltip>
          <template slot-scope="scope" >
            <el-input v-if="scope.row.edit" v-model="scope.row.detail" placeholder="请输入明细" clearable></el-input>
            <span v-else>{{scope.row.detail}}</span>
          </template>

        </el-table-column>-->
        <el-table-column label="消耗金额（元）" prop="consume" align="center">
          <template slot-scope="scope">
            <el-input v-if="scope.row.edit" v-model.number="scope.row.consume" type="number" @change="changeConsume(scope.row)" ></el-input>
            <span v-else :class="Number(scope.row.income) !== Number(scope.row.consume) ? 'error-color' : ''">
              {{scope.row.consume}}
              <el-popover trigger="hover"  placement="right">
                  <el-table :data="scope.row.consumeList">
                    <el-table-column width="120" property="finalConsume" label="消耗金额（元）" align="center"></el-table-column>
                    <el-table-column width="100" property="logTime" label="修改时间" align="center"></el-table-column>
                  </el-table>
                <i slot="reference" class="el-icon-question"></i>
              </el-popover>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="合同文件" prop="fileName" align="center" show-overflow-tooltip>
          <template slot-scope="scope" >
            <el-upload
              v-if="scope.row.edit"
              multiple
              :headers="uploadHeader()"
              :on-success="(response, file, fileList) => successUpload(response, file, fileList, scope.row)"
              :on-remove="removeUpload(scope.row)"
              :on-change="changeUpload"
              :action="uploadUrl()"
              accept=".pdf">
              <el-button size="small" type="primary">上传pdf文件</el-button>
            </el-upload>
            <el-button v-if="scope.row.fileName" type="text" style="color: #6E92E9;" @click="downloadFile(scope.row)">{{scope.row.fileName}}</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作时间" prop="createTime" align="center">
        </el-table-column>
        <el-table-column label="操作人" prop="createByName" align="center"></el-table-column>
        <el-table-column label="操作" prop="" align="center">
          <template slot-scope="scope">
            <el-button v-if="scope.row.edit" style="color: #E96E6E" @click="paging()" type="text">取消</el-button>
            <span v-if="scope.row.edit">|</span>
            <el-button style="color: #6E92E9" @click="clickUpdate(scope.row, scope.$index)" type="text">{{scope.row.edit ? '保存' : '修改'}}</el-button>
            <span>|</span>
            <el-button style="color: #E96E6E" @click="clickDelete(scope.row, scope.$index)" type="text">删除</el-button>
          </template>
        </el-table-column>

      </el-table>
      <el-pagination
        @size-change="changePageSize"
        @current-change="turnToPage"
        :current-page="queryInfo.pageIndex"
        :page-sizes="[5, 10, 20, 50, 100, 200]"
        :page-size="queryInfo.pageSize "
        layout="total, prev, pager, next, sizes, jumper"
        :total="totalPage"
        id="div-e-paging-id">
      </el-pagination>
    </div>
    <income-detail :data="addOrUpdateScope" :dialog-visible="incomeDetailDialogVisible" @dialogVisibleChange="changeIncomeDetailDialogVisible" @getIncomeDetailData="setIncomeDetailData"></income-detail>
  </div>
</template>

<script>
import {paging} from '../../../../api/customer/potential'
import Vue from 'vue'
import {incomeType} from '../../../../api/customer/enterprise'
import {getUserInfo} from '../../../../api/sys'
import BatchImport from '../Component/BatchImport'
import {deleteCooperation, saveCooperation, updateCooperation, exportCooperation} from '../../../../api/customer/cooperation'
import IncomeDetail from '../Component/IncomeDetail'
import {getDictList} from '../../../../api/customer/commom'
const objHasKey = require('lodash/has')
export default {
  name: 'enteprise-details-cooperation',
  components: {IncomeDetail, BatchImport},
  props: {
    id: {
      type: Number,
      default: null
    },
    form: {
      'customerId': '',
      'description': '',
      'income': '',
      'incomeDate': '',
      'detail': '',
      'fileName': '',
      'fileUrl': ''
    }
  },
  created () {
    this.getDictListOptions()
    this.getUserInfoReq()
    this.paging()
    this.getTypeOption()
  },
  data () {
    return {
      incomeDetailDialogVisible: false,
      addOrUpdateScope: {},
      tableData: [],
      typeOptions: [],
      dictListOptions: [],
      dataListLoading: false,
      // 明细金额
      subtotal: '',
      params: {
        name: ''
      },
      queryInfo: {
        pageIndex: 1,
        pageSize: 20
      },
      totalPage: 1,
      rules: {
        description: {
          required: true,
          message: '请输入合同简述'
        },
        income: {
          required: true,
          message: '请输入'
        }
      },
      userInfo: {}
    }
  },
  methods: {
    getDictListOptions () {
      let dataForm = {'dictCode': 'incomeAccount'}
      getDictList(dataForm, ({data}) => {
        this.dictListOptions = data
      })
    },
    showIncomeDetail (scope) {
      this.addOrUpdateScope = {
        row: scope.row,
        index: scope.$index
      }
      this.incomeDetailDialogVisible = true
    },
    changeIncomeDetailDialogVisible (val) {
      this.incomeDetailDialogVisible = val
    },
    setIncomeDetailData (data) {
      // console.log('detaildata', data)
      let detailText = ''
      let incomeDetailList = []
      if (data) {
        const {textList, tableData, subtotal, sum} = data
        textList.forEach((item) => { detailText += `${item.content}\n` })
        detailText = `进款总额：${sum}; ` + detailText
        // this.form.incomeDetail = detailText
        tableData.forEach((item) => {
          let incomeDetailItem = {}
          incomeDetailItem['typeId'] = item.typeId
          incomeDetailItem['subjectId'] = item.projectId
          incomeDetailItem['explain'] = item.explain
          incomeDetailItem['unitPrice'] = item.perPrice
          incomeDetailItem['amount'] = item.num
          incomeDetailItem['subtotal'] = item.perPrice * item.num
          // incomeDetailItem['sum'] = item.perPrice * item.num + item.tax
          incomeDetailItem['tax'] = item.tax
          incomeDetailList.push(incomeDetailItem)
        })
        const ColIndex = this.addOrUpdateScope.index
        const col = this.$refs.cooperationTableRefs.data[ColIndex]
        this.$set(col, 'detail', detailText)
        // this.$set(this.$refs.cooperationTableRefs.data[ColIndex], 'income', subtotal)
        this.$set(col, 'incomeDetailList', incomeDetailList)
        this.subtotal = subtotal

        // 进款金额校验
        if (objHasKey(col, 'income')) {
          if (Number(col.income) !== Number(sum)) {
            this.$confirm('进款金额与进款明细总计金额不同，请检查!', '提示',
              {
                confirmButtonText: '确 认',
                cancelButtonText: '取 消',
                showCancelButton: false,
                type: 'warning'
              })
          }
        }
        // subtotal为总计等于进款金额
        // this.form.subtotal = subtotal
        // this.form.income = subtotal
        // this.form.incomeDetailList = incomeDetailList
      }
    },
    uploadHeader () {
      return {
        'token': Vue.cookie.get('token')
      }
    },
    uploadUrl () {
      return this.$http.adornUrl('/ent/customer/file/upload')
    },
    paging () {
      this.dataListLoading = true
      paging(
        '/ent/customer/cooperation/paging',
        {
          'conditions': {
            'customerId': this.id,
            'createByName': this.params.name
          },
          'inOrder': '',
          'orderBy': '',
          'pageNum': this.queryInfo.pageIndex,
          'pageSize': this.queryInfo.pageSize
        },
        'post',
        (data) => {
          this.tableData = data.data.records
          this.totalPage = data.total
          this.dataListLoading = false
        }
      )
    },
    clearName () {
      this.params.name = ''
      this.paging()
    },
    clickReset () {
      // this.$refs.paramsRefs.resetFields()
      this.params.name = ''
      this.paging()
    },
    clickSearch () {
      this.paging()
    },
    changePageSize (val) {
      this.queryInfo.pageSize = val
    },
    turnToPage (val) {
      this.queryInfo.pageIndex = val
    },
    downloadFile (row) {
      window.open(row.fileUrl)
    },
    checkForm () {

    },
    checkIncome (val) {

    },
    // 表单校验
    formValidator (row = {}, validateList = []) {
      return validateList.every((key) => {
        console.log(key)
        if (objHasKey(row, key) && row[`${key}`]) {
          return true
        } else {
          return false
        }
      })
    },
    clickUpdate (row, index) {
      // console.log('rowaa', row)
      // 所有表单结果校验合格
      let isAllValidity = false
      // 表单非空校验,使用箭头函数立即执行
      const ok = (() => {
        // 进款金额小于0时不校验进款账号
        if (row.income < 0) {
          return this.formValidator(row, ['income', 'detail', 'incomeDate'])
        } else {
          return this.formValidator(row, ['income', 'detail', 'incomeAccountId', 'incomeDate'])
        }
      })()

      if (!row.edit) {
        row.edit = true
        this.$set(this.tableData, index, row)
        return
      }
      let sum = 0
        // 退款的总额为负数
      let sumList = row.incomeDetailList.map((item) => {
        if (item.typeId === 3) {
          return 0 - item.subtotal - item.tax
        } else {
          return item.subtotal + item.tax
        }
      })
      sum = sumList.reduce((prev, curr) => prev + curr)

      if (!ok) {
        isAllValidity = false
        this.$message.warning('请检查信息是否填写完整！')
      } else if (Number(sum) !== Number(row.income)) {
        isAllValidity = false
        this.$confirm('进款金额与进款明细总计金额不同，请检查!', '提示',
          {
            confirmButtonText: '确 认',
            cancelButtonText: '取 消',
            showCancelButton: false,
            type: 'warning'
          })
      } else if (Math.abs(row.consume) > Math.abs(row.income)) {
        isAllValidity = false
        this.$confirm('消耗金额不得大于进款进额！', '提示', {
          confirmButtonText: '确认',
          type: 'warning',
          showCancelButton: false
        })
      } else {
        isAllValidity = true
      }

      if (isAllValidity) {
        let formData = {
          'description': row.description,
          'income': row.income,
          'incomeDate': row.incomeDate,
          'detail': row.detail,
          'fileName': row.fileName,
          'fileUrl': row.fileUrl,
          'customerId': this.id,
          'perfor': row.perfor || 0,
          'typeId': row.typeId,
          'incomeAccountId': row.incomeAccountId || null,
          'incomeDetailList': row.incomeDetailList,
          'incomeAccount': this.getSelectedDictOptionName(row.incomeAccountId),
          'consume': row.consume || 0
        }

        let out = this
        if (row.id) {
          formData.id = row.id
          updateCooperation(formData,
            (data) => {
              row.edit = false
              out.$set(out.tableData, index, row)
              out.paging()
            })
        } else {
          saveCooperation(formData,
            function (data) {
              out.paging()
            })
        }
      }
    },

    clickDelete (row, index) {
      let out = this
      this.$confirm(
        `确认要删除吗?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (row.id) {
            deleteCooperation(
              row.id,
              function (data) { out.tableData.splice(index, 1) })
          } else {
            out.tableData.splice(index, 1)
          }
        })
    },

    // 添加
    addData () {
      this.tableData.push({
        edit: true
      })
    },
    // 确认添加
    confirmAdd (row, formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          row.edit = false
        }
      })
    },
    // 修改
    editData (row) {
      row.edit = true
    },
    // 删除
    deleteData (row, index) {
      this.formData.tableData.splice(index, 1)
    },
    successUpload (response, file, fileList, row) {
      let fileUrl = ''
      if (response.code === 0) {
        let data = response.data
        fileUrl = data.remoteUrl + data.fileName
        row.fileUrl = fileUrl
        row.fileName = file.name
      } else {
        this.$message.error(response.msg)
      }

      if (fileList.length > 1) {
        fileList.splice(0, 1)
      }
    },
    removeUpload (row) {
    },
    changeUpload (file, fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1)
      }
    },
    getTypeOption () {
      this.typeOptions = incomeType
    },
    getUserInfoReq () {
      getUserInfo(
        (data) => { this.userInfo = data.user }
      )
    },
    clickExport () {
      exportCooperation(
        {
          'customerId': this.id,
          'createByName': this.userInfo.nickName
        },
        '合作记录')
    },
    getSelectedDictOptionName (id) {
      if (this.dictListOptions && id) {
        // console.log('option', this.dictListOptions.filter(item => item.id === id))
        const option = this.dictListOptions.filter(item => item.id === id)
        if (option) {
          return this.dictListOptions.filter(item => item.id === id)[0].name
        } else {
          return null
        }
      } else {
        return null
      }
    },
    changeIncomeAccount (option) {
    },
    changeIncome (val, row) {
     // console.log('val', val)
     // console.log('row', row)
      if (row.incomeDetailList) {
        let sumList = row.incomeDetailList.map((item) => {
          if (item.typeId === 3) {
            return 0 - item.subtotal - item.tax
          } else {
            return item.subtotal + item.tax
          }
        })
        let sum = sumList.reduce((prev, curr) => prev + curr)
        if (Number(sum) !== Number(val)) {
          this.$confirm('进款金额与进款明细总计金额不同，请检查!', '提示',
            {
              confirmButtonText: '确 认',
              cancelButtonText: '取 消',
              showCancelButton: false,
              type: 'warning'
            })
        }
      }
    },
    changeConsume (row) {
      if (Math.abs(row.consume) > Math.abs(row.income)) {
        this.$confirm('消耗金额不得大于进款进额！', '提示', {
          confirmButtonText: '确认',
          type: 'warning',
          showCancelButton: false
        })
      }
    }
  },
  computed: {

  }
}
</script>

<style lang="less" scoped>
.div-inquire{
  display: flex;
  justify-content: space-between;
  .div-inquire-left{
    display: flex;
    align-items: flex-start;
  }
  .div-inquire-right{
    display: flex;
    justify-content: flex-end;
    align-items: flex-start;
  }
}

.error-color{
  color: red;
}

.warning-color{
  color: darkorange;
}
</style>
